from playwright.sync_api import sync_playwright
from datetime import datetime
from urllib.parse import urlparse
import json
import time
import requests
from fake_useragent import UserAgent


# 获取代理
def get_ua():
    common_desktop_and_mobile = ['chrome', 'firefox', 'safari', 'edge', 'opera']
    while True:
        user_agent = UserAgent(os=["windows", "macos"],platforms=["pc"]).random
        if any(device in user_agent.lower() for device in common_desktop_and_mobile):
            return user_agent


def fetch_ip_country(context):
    ip, country = "", ""
    try:
        page = context.new_page()
        page.goto("http://ipinfo.io/json", timeout=10000)
        info = json.loads(page.inner_text("body"))
        ip = info.get("ip", "")
        country = info.get("country", "")
        page.close()
    except:
        pass
    return ip, country


def trace_redirect_with_browser(url, ipport=None, headless=True):
    all_urls = []

    with sync_playwright() as p:
        proxy_config = {}
        if ipport:
            proxy_config = {
                "server": f"socks5://{ipport.get('ip')}:{ipport.get('port')}"
            }

        browser = p.chromium.launch(headless=headless)
        context = browser.new_context(
            **({"proxy": proxy_config} if proxy_config else {}),
            user_agent=get_ua()
        )
        page = context.new_page()

        def on_request(request):
            if request.is_navigation_request():
                all_urls.append(request.url)

        page.on("request", on_request)
        ip, country = fetch_ip_country(context)
        print(f"🌐 正在打开页面: {url}")
        print(f"🌐 当前代理IP: {ip or 'N/A'} | 国家: {country or 'N/A'}")
        try:
            page.goto(url, timeout=30000, wait_until="domcontentloaded")
        except Exception as e:
            print(f"⚠️ 页面跳转异常: {e}")

        # 观察跳转变化
        for _ in range(10):
            print(f"⏳ 当前URL: {page.url}")
            time.sleep(1)

        if not all_urls or all_urls[-1] != page.url:
            all_urls.append(page.url)

        browser.close()

    print("\n🔁 跳转链：")
    for i, u in enumerate(all_urls, 1):
        print(f"[{i}] {u}")

    return all_urls


def get_proxy6(country="US"):
    # https://www.ipwo.net/user/ucenter/api_extraction 
    url = f"https://www.ipwo.net/api/proxy/get_proxy_ip?num=1&regions={country}&protocol=socks5&return_type=json&lb=4&sb="
    i = 0
    while i < 5:
        # 每次提取10个，放入线程中
        resp = requests.get(url=url, timeout=5)
        try:
            if resp.status_code == 200:
                dataBean = json.loads(resp.text)
                pass #print(dataBean)
            else:
                i += 1
                pass #print("获取失败")
                time.sleep(1)
                continue
        except ValueError:
            i += 1
            pass #print("获取失败")
            time.sleep(1)
            continue
        else:
            # 解析json数组，获取ip和port
            pass #print("code=", dataBean["code"])
            code = dataBean["code"]
            if code == 0:
                for proxy in dataBean["data"]:
                    return proxy  # {'ip': '43.153.97.48', 'port': 10448}
        i += 1
        pass #print(i)

# 示例调用
if __name__ == "__main__":
    test_url = "https://pb.eclicklink.com/5ZS8GM/7XDN2/"
    country = "US"
    # test_url = "https://pb.eclicklink.com/5ZS8GM/26QJFJ86/"
    # country = "CA"
    # test_url = "https://pb.eclicklink.com/5ZS8GM/3LBTKGZ1/"
    # country = "US"
    test_url = "https://link.smilekols.com/log?clickid=%7B%7BDATETIME%7D%7D&cmpgn=1008504&pub=1078564&path=https%3A%2F%2Fwww.primevideo.com"
    country = "BR"
    # test_url = "https://pb.eclicklink.com/5ZS8GM/6SNZDMNR/"
    # country = "US"
    # test_url = "https://clxs.clixyes.com/clix?pid=1069349&aid=1001773&clixid=%7B%7BDATETIME%7D%7D&link=https%3A%2F%2Fwww.crocs.com"
    # country = "US"
    # test_url = "https://kn.kreatornow.com/kn/click?prop=1069331&brand_id=1004889&mark=%7B%7BDATETIME%7D%7D&dest=https%3A%2F%2Fwww.levi.com%2FUS%2Fen_US%2F"
    # country = "US"
    # test_url = "https://pb.eclicklink.com/5ZS8GM/9RHQ1JGJ/"
    # country = "US"
    for i in range(10):
        ipport = get_proxy6(country)
        # pass #print(ipport)
        trace_redirect_with_browser(test_url, ipport=ipport, headless=True)
        break